/**
 *
 */
package com.ybkj.daijia.api.boss.v1;

import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.member.Error;
import com.ybkj.daijia.api.member.ErrorConstant;
import com.ybkj.daijia.api.member.transport.ResultTransport;
import com.ybkj.daijia.common.Distance;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.event.model.OrderCreateEvent;
import com.ybkj.daijia.server.event.model.OrderNewRushEvent;
import com.ybkj.daijia.server.event.model.OrderRecordEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Admin;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.Role;
import com.ybkj.daijia.server.model.RoleAuthority;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.scheduler.ThreadControl;
import com.ybkj.daijia.server.service.AdminService;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.BossService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.RateService;
import com.ybkj.daijia.server.service.RoleAuthorityService;
import com.ybkj.daijia.server.service.RoleService;
import com.ybkj.daijia.server.service.UsuallyDriverService;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author bo
 *
 */
@Controller("BossV1Controller")
@RequestMapping(value = "boss/api/rest/v1")
public class BossController {

    private static final Logger logger = LoggerFactory.getLogger(BossController.class);

    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberAccountService memberAccountService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private RateService rateService;
    @Autowired
    private UsuallyDriverService usuallyDriverService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleAuthorityService roleAuthorityService;
    @Autowired
    private BossService bossService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;


    private boolean hasPermission(Admin admin, String permission) {
        List<Role> roles = roleService.findByAdmin(admin.getId());
        if (!CollectionUtils.isEmpty(roles)) {
            for (Role role : roles) {
                List<RoleAuthority> roleAuthorities = roleAuthorityService
                    .selectByRoleId(role.getId());
                if (!CollectionUtils.isEmpty(roleAuthorities)) {
                    for (RoleAuthority roleAuthority : roleAuthorities) {
                        if (roleAuthority.getAuthority().equals(permission)) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    /**
     * 首页数据
     * @return
     */
    @RequestMapping(value = "indexData")
    public @ResponseBody
    ResultTransport indexData(HttpServletResponse response, Long userId) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        logger.debug("recv userId:{}", userId);

        if (null == userId) {
            return ResultTransport.getErrorBy(new Error(-1, "参数错误"));
        }

        Admin admin = adminService.findOne(userId);
        if (null == admin) {
            return ResultTransport.getErrorBy(new Error(-1, "账号不存在"));
        }

        if (!hasPermission(admin, "bossreporting")) {
            return ResultTransport.getErrorBy(new Error(-1, "您没有该权限"));
        }

        try {

            Map<String, Object> map = bossService.indexData(admin);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(map);
            return instance;

        } catch (Exception e) {
            logger.error("api boss v1 indexData error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }


    /**
     * 登陆
     * @return
     */
    @RequestMapping(value = "login")
    public @ResponseBody
    ResultTransport login(HttpServletResponse response, HttpServletRequest req,
        String username, String password) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        logger.debug("recv username:{},password:{}", username, password);

        Principal temp_principal = new Principal(0L, username);
        if (req.getHeader("x-forwarded-for") == null) {
            temp_principal.setHost(req.getRemoteAddr());
        } else {
            temp_principal.setHost(req.getHeader("x-forwarded-for"));
        }

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {

            String detail = "【%s】登陆系统，用户名/密码为空，APP登陆。";
            OperationLogEvent operationLogEvent = new OperationLogEvent(temp_principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            return ResultTransport.getErrorBy(new Error(-1, "参数错误"));
        }

        try {

            Admin admin = adminService.findByUsername(username);

            if (null == admin) {

                String detail = "【%s】登陆系统，用户不存在，APP登陆。";
                OperationLogEvent operationLogEvent = new OperationLogEvent(temp_principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);

                return ResultTransport.getErrorBy(new Error(-1, "用户不存在"));
            }

            if (!hasPermission(admin, "bossreporting")) {

                String detail = "【%s】登陆系统，没有权限，APP登陆。";
                OperationLogEvent operationLogEvent = new OperationLogEvent(temp_principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);

                return ResultTransport.getErrorBy(new Error(-1, "您没有该权限"));
            }

            if (admin.getIsLocked()) { //判断管理员是否禁用

                String detail = "【%s】登陆系统，用户被禁用，APP登陆。";
                OperationLogEvent operationLogEvent = new OperationLogEvent(temp_principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);

                return ResultTransport.getErrorBy(new Error(-1, "用户被禁用"));
            }

            Sha256Hash hash = new Sha256Hash(password);

            if (!admin.getPassword().equals(hash.toBase64())) {

                String detail = "【%s】登陆系统，密码错误，APP登陆。";
                OperationLogEvent operationLogEvent = new OperationLogEvent(temp_principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);

                return ResultTransport.getErrorBy(new Error(-1, "密码错误"));
            }

            Company company = companyService.findOne(admin.getCompanyId());

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userId", admin.getId());
            map.put("userName", admin.getUsername());
            map.put("companyName", company.getAbbreviation());
            map.put("companyLng", company.getLongitude());
            map.put("companyLat", company.getLatitude());

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(map);

            Principal principal = new Principal(admin.getId(), admin.getUsername());
            if (null != company) {
                principal.setCompanyName(company.getCompanyName());
                principal.setCompanyAbbreviation(company.getAbbreviation());
                principal.setCompanyId(company.getId());
                principal.setCompanyType(company.isCompanyType());
            }
            principal.setHost(temp_principal.getHost());
            String detail = "【%s】登陆系统，登陆成功，APP登陆。";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            return instance;

        } catch (Exception e) {
            logger.error("api boss v1 login error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 登陆
     * @return
     */
    @RequestMapping(value = "login2")
    public @ResponseBody
    ResultTransport login2(HttpServletResponse response, HttpServletRequest req,
        String username, String password) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        logger.debug("recv username:{},password:{}", username, password);

        Principal temp_principal = new Principal(0L, username);
        if (req.getHeader("x-forwarded-for") == null) {
            temp_principal.setHost(req.getRemoteAddr());
        } else {
            temp_principal.setHost(req.getHeader("x-forwarded-for"));
        }

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {

            String detail = "【%s】登陆系统，用户名/密码为空，APP登陆。";
            OperationLogEvent operationLogEvent = new OperationLogEvent(temp_principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            return ResultTransport.getErrorBy(new Error(-1, "参数错误"));
        }

        try {

            Admin admin = adminService.findByUsername(username);

            if (null == admin) {

                String detail = "【%s】登陆系统，用户不存在，APP登陆。";
                OperationLogEvent operationLogEvent = new OperationLogEvent(temp_principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);

                return ResultTransport.getErrorBy(new Error(-1, "用户不存在"));
            }

            if (!hasPermission(admin, "bossreporting")) {

                String detail = "【%s】登陆系统，没有权限，APP登陆。";
                OperationLogEvent operationLogEvent = new OperationLogEvent(temp_principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);

                return ResultTransport.getErrorBy(new Error(-1, "您没有该权限"));
            }

            if (admin.getIsLocked()) { //判断管理员是否禁用

                String detail = "【%s】登陆系统，用户被禁用，APP登陆。";
                OperationLogEvent operationLogEvent = new OperationLogEvent(temp_principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);

                return ResultTransport.getErrorBy(new Error(-1, "用户被禁用"));
            }

            Sha256Hash hash = new Sha256Hash(password, Admin.SALT_KEY);

            if (!admin.getPassword().equals(hash.toBase64())) {

                String detail = "【%s】登陆系统，密码错误，APP登陆。";
                OperationLogEvent operationLogEvent = new OperationLogEvent(temp_principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);

                return ResultTransport.getErrorBy(new Error(-1, "密码错误"));
            }

            Company company = companyService.findOne(admin.getCompanyId());

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userId", admin.getId());
            map.put("userName", admin.getUsername());
            map.put("companyName", company.getAbbreviation());
            map.put("companyLng", company.getLongitude());
            map.put("companyLat", company.getLatitude());

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(map);

            Principal principal = new Principal(admin.getId(), admin.getUsername());
            if (null != company) {
                principal.setCompanyName(company.getCompanyName());
                principal.setCompanyAbbreviation(company.getAbbreviation());
                principal.setCompanyId(company.getId());
                principal.setCompanyType(company.isCompanyType());
            }
            principal.setHost(temp_principal.getHost());
            String detail = "【%s】登陆系统，登陆成功，APP登陆。";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            return instance;

        } catch (Exception e) {
            logger.error("api boss v1 login error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 所有新单
     * @return
     */
    @RequestMapping(value = "allNewOrder")
    public @ResponseBody
    ResultTransport todayOrder(
        HttpServletResponse response, Long userId) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        logger.debug("recv userId:{}", userId);

        if (null == userId) {
            return ResultTransport.getErrorBy(new Error(-1, "参数错误"));
        }

        Admin admin = adminService.findOne(userId);
        if (null == admin) {
            return ResultTransport.getErrorBy(new Error(-1, "账号不存在"));
        }

        if (!hasPermission(admin, "bossreporting")) {
            return ResultTransport.getErrorBy(new Error(-1, "您没有该权限"));
        }

        try {

            List<Order> orderlist = bossService.allNewOrder(admin);

            List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(orderlist)) {

                SimpleDateFormat formatter = com.ybkj.daijia.constant.DateConstant.DATE_TIME;

                for (Order order : orderlist) {

                    Company company = companyService.findOne(order.getCompanyId());

                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("orderId", order.getId());
                    map.put("orderNumber", order.getOrderNumber());
                    map.put("orderBookTime", formatter.format(order.getServerTime()));
                    map.put("orderBookAddress", order.getFromPlace());
                    map.put("orderCompany", company.getAbbreviation());
                    map.put("orderType", order.getOrderType());
                    map.put("orderFromSource", order.getFromSource());
                    map.put("clientName", order.getClientName());
                    map.put("clientPhone", order.getClientPhone());
                    mapList.add(map);
                }
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(mapList);

            return instance;

        } catch (Exception e) {
            logger.error("api boss v1 allNewOrder error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }


    /**
     * 销单
     * @return
     */
    @RequestMapping(value = "cancelOrder")
    public @ResponseBody
    ResultTransport cancelOrder(HttpServletResponse response,
        Long userId, String content, Long orderId) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        logger.debug("recv userId:{},content:{},orderId:{}", userId, content, orderId);

        if (null == userId || StringUtils.isBlank(content) || null == orderId) {
            return ResultTransport.getErrorBy(new Error(-1, "参数错误"));
        }

        Admin admin = adminService.findOne(userId);
        if (null == admin) {
            return ResultTransport.getErrorBy(new Error(-1, "账号不存在"));
        }

        if (!hasPermission(admin, "bossreporting")) {
            return ResultTransport.getErrorBy(new Error(-1, "您没有该权限"));
        }

        try {

            Order order = orderService.findOne(orderId);

            if (null == order) {
                return ResultTransport.getErrorBy(new Error(-1, "订单不存在"));
            }

            if (order.getStatus().equals(Order.ORDER_STATUS_NEW)) {

                bossService.bossCancel(admin, order, content);

                ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
                instance.setData(null);

                //日志

                return instance;
            } else {
                return ResultTransport.getErrorBy(new Error(-1, "当前订单状态不能销单"));
            }

        } catch (Exception e) {
            logger.error("api boss v1 cancelOrder error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 获取订单推荐服务人员
     * @return
     */
    @RequestMapping(value = "getTuijianDrivers")
    public @ResponseBody
    ResultTransport getTuijianDrivers(HttpServletResponse response,
        Long userId, Long orderId, String keyWord) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        logger.debug("recv userId:{},orderId:{},keyWord:{}", userId, orderId, keyWord);

        if (null == userId || null == orderId) {
            return ResultTransport.getErrorBy(new Error(-1, "参数错误"));
        }

        Admin admin = adminService.findOne(userId);
        if (null == admin) {
            return ResultTransport.getErrorBy(new Error(-1, "账号不存在"));
        }

        if (!hasPermission(admin, "bossreporting")) {
            return ResultTransport.getErrorBy(new Error(-1, "您没有该权限"));
        }

        try {

            Order order = orderService.findOne(orderId);

            if (null == order) {
                return ResultTransport.getErrorBy(new Error(-1, "订单不存在"));
            }

            Setting setting = settingUtils.get();
            List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();

            //
            if (StringUtils.isNotBlank(keyWord)) {
                List<Driver> drivers = driverService.queryByKeyword(keyWord);

                if (!CollectionUtils.isEmpty(drivers)) {

                    for (Driver driver : drivers) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("driverId", driver.getId());
                        map.put("driverName", driver.getRealname());
                        map.put("driverPhone", driver.getPhone());
                        map.put("driverAddress", driver.getCurrentAddress());
                        map.put("driverUserName", driver.getUsername());
                        map.put("driverHead",
                            setting.getWebUrl() + "/upload/driver/" + driver.getPhoto());
                        map.put("driverStar", driver.getStarLevel());
                        map.put("driverTimes", driver.getDriveTimes());
                        map.put("driverJialing", driver.getjialing());
                        double distance = Distance
                            .doubleVal(order.getClientLatitude(), order.getClientLongitude(),
                                driver.getLatitude(), driver.getLongitude());
                        DecimalFormat df = new DecimalFormat("#.00");
                        if (distance >= 1) {
                            map.put("driverDistance", df.format(distance) + "公里");
                        } else {
                            map.put("driverDistance", (long) (distance * 1000) + "米");
                        }
                        map.put("driverMeter", distance * 1000);
                        map.put("driverLng", driver.getLongitude());
                        map.put("driverLat", driver.getLatitude());
                        mapList.add(map);
                    }

                }

                ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
                instance.setData(mapList);

                return instance;
            }

            Setting oldsetting = settingUtils.get();
            Double paidanKm = oldsetting.getPaidanKm();

            Double orderlng = order.getClientLongitude();
            Double orderlat = order.getClientLatitude();

            //附近服务人员
            List<Driver> drivers = driverService
                .queryNearly(orderlng, orderlat, paidanKm, Driver.DriverJobType.daijia.toString());
            if (CollectionUtils.isEmpty(drivers)) {
                drivers = new LinkedList<Driver>();
            }

            //查询在执行中的已完成时间在 半小时内的，目的地与新单相同的单 服务人员
            List<Order> orders = orderService.queryNearBy(orderlng, orderlat, paidanKm);
            if (!CollectionUtils.isEmpty(orders)) {
                for (Order order2 : orders) {
                    if (null != order2.getDriverId()) {
                        Driver driver = driverService.findOne(order2.getDriverId());
                        Date arriveTime = HttpClientUtil
                            .getDateByTwoPoints(driver.getLongitude(), driver.getLatitude(),
                                order2.getToPlaceLongitude(), order2.getToPlaceLatitude());

                        Long time = (order.getServerTime().getTime() - arriveTime.getTime()) / (1000
                            * 60); //预约时间 - 到达时间

                        if (null != arriveTime && time >= 0 && time <= 60) {
                            drivers.add(driver);
                        }
                    }
                }
            }

            if (CollectionUtils.isEmpty(drivers)) {
                drivers = driverService
                    .queryNearly(orderlng, orderlat, 40d, Driver.DriverJobType.daijia.toString());
            }

            if (!CollectionUtils.isEmpty(drivers)) {

                //计算距离
                for (Driver driver : drivers) {
                    double distance = Distance
                        .doubleVal(orderlat, orderlng, driver.getLatitude(), driver.getLongitude());
                    driver.setDistance(distance);
                }

                Collections.sort(drivers, new Comparator<Driver>() {
                    public int compare(Driver arg0, Driver arg1) {
                        return arg0.getDistance().compareTo(arg1.getDistance());
                    }
                });

                for (Driver driver : drivers) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("driverId", driver.getId());
                    map.put("driverName", driver.getRealname());
                    map.put("driverPhone", driver.getPhone());
                    map.put("driverAddress", driver.getCurrentAddress());
                    map.put("driverUserName", driver.getUsername());
                    map.put("driverHead",
                        setting.getWebUrl() + "/upload/driver/" + driver.getPhoto());
                    map.put("driverStar", driver.getStarLevel());
                    map.put("driverTimes", driver.getDriveTimes());
                    map.put("driverJialing", driver.getjialing());
                    DecimalFormat df = new DecimalFormat("#.00");
                    if (driver.getDistance() >= 1) {
                        map.put("driverDistance", df.format(driver.getDistance()) + "公里");
                    } else {
                        map.put("driverDistance", (long) (driver.getDistance() * 1000) + "米");
                    }
                    map.put("driverMeter", driver.getDistance() * 1000);
                    map.put("driverLng", driver.getLongitude());
                    map.put("driverLat", driver.getLatitude());
                    mapList.add(map);
                }

            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(mapList);

            return instance;

        } catch (Exception e) {
            logger.error("api boss v1 getTuijianDrivers error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 上班、跑单服务人员列表
     * @return
     */
    @RequestMapping(value = "getWorkingDrivers")
    public @ResponseBody
    ResultTransport getWorkingDrivers(HttpServletResponse response,
        Long userId) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        logger.debug("recv userId:{}", userId);

        if (null == userId) {
            return ResultTransport.getErrorBy(new Error(-1, "参数错误"));
        }

        Admin admin = adminService.findOne(userId);
        if (null == admin) {
            return ResultTransport.getErrorBy(new Error(-1, "账号不存在"));
        }

        if (!hasPermission(admin, "bossreporting")) {
            return ResultTransport.getErrorBy(new Error(-1, "您没有该权限"));
        }

        try {

            List<Driver> drivers = bossService.getWorkingDrivers(admin);

            List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();

            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(drivers)) {

                Setting setting = settingUtils.get();

                for (Driver driver : drivers) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("driverId", driver.getId());
                    map.put("driverName", driver.getRealname());
                    map.put("driverStatus", driver.getStatus());
                    map.put("driverPhone", driver.getPhone());
                    map.put("driverAddress", driver.getCurrentAddress());
                    map.put("driverUserName", driver.getUsername());
                    map.put("driverHead",
                        setting.getWebUrl() + "/upload/driver/" + driver.getPhoto());
                    map.put("driverStar", driver.getStarLevel());
                    map.put("driverTimes", driver.getDriveTimes());
                    map.put("driverJialing", driver.getjialing());
                    map.put("driverLng", driver.getLongitude());
                    map.put("driverLat", driver.getLatitude());
                    mapList.add(map);
                }

            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(mapList);
            return instance;

        } catch (Exception e) {
            logger.error("api boss v1 getWorkingDrivers error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * @return
     */
    @RequestMapping(value = "getSetting")
    public @ResponseBody
    ResultTransport getSetting(HttpServletResponse response, Long userId) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        logger.debug("recv userId:{}", userId);

        if (null == userId) {
            return ResultTransport.getErrorBy(new Error(-1, "参数错误"));
        }

        Admin admin = adminService.findOne(userId);
        if (null == admin) {
            return ResultTransport.getErrorBy(new Error(-1, "账号不存在"));
        }

        if (!hasPermission(admin, "bossreporting")) {
            return ResultTransport.getErrorBy(new Error(-1, "您没有该权限"));
        }

        try {

            //APP配置
            Map<String, Object> settingMap = new HashMap<String, Object>();
            Setting setting = settingUtils.get();
            settingMap.put("allowRushOrder", setting.isAllowRushOrder());
            settingMap.put("allowDriverZhuandan", setting.isAllowDriverZhuandan());
            settingMap.put("autoPaidan", setting.isAutoPaidan());
            settingMap.put("paidanKm", setting.getPaidanKm());

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(settingMap);
            return instance;

        } catch (Exception e) {
            logger.error("api boss v1 getSetting error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * @return
     */
    @RequestMapping(value = "changeSetting")
    public @ResponseBody
    ResultTransport changeSetting(HttpServletResponse response, Long userId,
        boolean allowRushOrder, boolean allowDriverZhuandan, boolean autoPaidan, Double paidanKm) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        logger.debug(
            "recv userId:{},allowRushOrder:{},allowDriverZhuandan:{},autoPaidan:{}，paidanKm:{}",
            userId, allowRushOrder, allowDriverZhuandan, autoPaidan, paidanKm);

        if (null == userId || null == paidanKm) {
            return ResultTransport.getErrorBy(new Error(-1, "参数错误"));
        }

        Admin admin = adminService.findOne(userId);
        if (null == admin) {
            return ResultTransport.getErrorBy(new Error(-1, "账号不存在"));
        }

        if (!hasPermission(admin, "bossreporting")) {
            return ResultTransport.getErrorBy(new Error(-1, "您没有该权限"));
        }

        try {

            Setting oldsetting = settingUtils.get();
            oldsetting.setAllowRushOrder(allowRushOrder);
            oldsetting.setAllowDriverZhuandan(allowDriverZhuandan);
            oldsetting.setAutoPaidan(autoPaidan);
            oldsetting.setPaidanKm(paidanKm);
            settingUtils.set(oldsetting);

            ThreadControl.SysAutoRunning = autoPaidan;

            //APP配置
            Map<String, Object> settingMap = new HashMap<String, Object>();
            Setting setting = settingUtils.get();
            settingMap.put("allowRushOrder", setting.isAllowRushOrder());
            settingMap.put("allowDriverZhuandan", setting.isAllowDriverZhuandan());
            settingMap.put("autoPaidan", setting.isAutoPaidan());
            settingMap.put("paidanKm", setting.getPaidanKm());

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(settingMap);
            return instance;

        } catch (Exception e) {
            logger.error("api boss v1 changeSetting error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 下单
     * @return
     */
    @RequestMapping(value = "createOrder")
    public synchronized @ResponseBody
    ResultTransport createOrder(HttpServletResponse response,
        Long userId, String clientPhone, String clientName, Integer driverNum,
        String fromPlace, Double longitude, Double latitude, String fromSource, String memo) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        logger.debug(
            "recv userId:{},clientPhone:{},clientName:{},driverNum:{},fromPlace:{},longitude:{},latitude:{},fromSource:{},memo:{}",
            userId, clientPhone, clientName, driverNum, fromPlace, fromSource, memo);

        if (null == userId || null == driverNum || StringUtils.isBlank(clientPhone) || StringUtils
            .isBlank(clientName)
            || StringUtils.isBlank(fromPlace) || StringUtils.isBlank(fromSource)) {
            return ResultTransport.getErrorBy(new Error(-1, "参数错误"));
        }

        Admin admin = adminService.findOne(userId);
        if (null == admin) {
            return ResultTransport.getErrorBy(new Error(-1, "账号不存在"));
        }

        if (!hasPermission(admin, "bossreporting")) {
            return ResultTransport.getErrorBy(new Error(-1, "您没有该权限"));
        }

        String regex = "^[0-9]*$";
        if (!Pattern.matches(regex, clientPhone)) {
            return ResultTransport.getErrorBy(new Error(-1, "手机号码不合法"));
        }

        try {

            Company company = companyService.findOne(admin.getCompanyId());

            Order order = new Order();
            try {
                if (null == longitude || null == latitude) {
                    Result<Map<String, Double>> fromPlaceVo = HttpClientUtil
                        .getLngAndLatByPlace(fromPlace, company.getCityName());

                    if (fromPlaceVo.isSuccess()) {
                        Map<String, Double> fromPlaceMap = fromPlaceVo.getResult();
                        order.setClientLongitude(fromPlaceMap.get("lng"));
                        order.setClientLatitude(fromPlaceMap.get("lat"));
                    } else {
                        order.setClientLongitude(company.getLongitude());
                        order.setClientLatitude(company.getLatitude());
                    }
                } else {
                    order.setClientLongitude(longitude);
                    order.setClientLatitude(latitude);
                }

            } catch (Exception e) {
                logger.debug(e.getMessage());
            }

            Passenger passenger = memberService.findOnePassengerByPhone(clientPhone);

            order.setFromPlace(fromPlace);
            order.setServerTime(new Date());
            order.setClientName(clientName);
            order.setClientPhone(clientPhone);
            order.setFromSource(fromSource);
            order.setMemo(memo);

            List<Order> newOrders = bossService.createOrder(admin, company, order, driverNum);

            for (Order order2 : newOrders) {
                OrderCreateEvent event = new OrderCreateEvent(order2);
                applicationEventMulticaster.multicastEvent(event);

                OrderRecordEvent orderRecordEvent = new OrderRecordEvent(order2);
                applicationEventMulticaster.multicastEvent(orderRecordEvent);
            }

            OrderNewRushEvent newRushEvent = new OrderNewRushEvent(newOrders);
            applicationEventMulticaster.multicastEvent(newRushEvent);

            if (null == passenger) {
                passenger = memberService.findOnePassengerByPhone(order.getClientPhone());
                ReactorVo rVo = new ReactorVo();
                rVo.setPassenger(passenger);
                rVo.setActivityEvent(ActivityEvent.newRegister);
                ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                applicationEventMulticaster.multicastEvent(activityCheckEvent);
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(null);

            return instance;

        } catch (Exception e) {
            logger.error("api boss v1 createOrder error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * @return
     */
    @RequestMapping(value = "getMemberInfo")
    public @ResponseBody
    ResultTransport getMemberInfo(HttpServletResponse response, Long userId, String phone) {

        response.setHeader("Access-Control-Allow-Origin", "*");

        logger.debug("recv userId:{},phone:{}", userId, phone);

        if (null == userId || StringUtils.isBlank(phone)) {
            return ResultTransport.getErrorBy(new Error(-1, "参数错误"));
        }

        Admin admin = adminService.findOne(userId);
        if (null == admin) {
            return ResultTransport.getErrorBy(new Error(-1, "账号不存在"));
        }

        if (!hasPermission(admin, "bossreporting")) {
            return ResultTransport.getErrorBy(new Error(-1, "您没有该权限"));
        }

        try {

            Passenger passenger = memberService.findOnePassengerByPhone(phone);
            if (null == passenger) {
                return ResultTransport.getErrorBy(new Error(-1, "未找到客户信息"));
            }

            //APP配置
            Map<String, Object> settingMap = new HashMap<String, Object>();

            settingMap.put("name", passenger.getName());

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(settingMap);
            return instance;

        } catch (Exception e) {
            logger.error("api boss v1 getMemberInfo error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

}
